package com.rcklos.NettyLentMe.netty;

import com.rcklos.NettyLentMe.ServerConfig;
import com.rcklos.NettyLentMe.protocol.protobuf.MessageProtobuf;

import com.rcklos.NettyLentMe.netty.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

public class Server {
	
	public void startServer() {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		
		try {
			//辅助启动类
			ServerBootstrap bootstrap= new ServerBootstrap();
			bootstrap.group(boss, worker);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					// TODO Auto-generated method stub
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast("frameEncoder", new LengthFieldPrepender(2));
					pipeline.addLast("frameDecoder",new LengthFieldBasedFrameDecoder(6355, 0, 2, 0, 2));
					pipeline.addLast("protobufDecoder",new ProtobufDecoder(MessageProtobuf.Msg.getDefaultInstance()));
					pipeline.addLast("protobufEncoder", new ProtobufEncoder());
					pipeline.addLast(new ServerHandler()); // 这一句绑定了Handler
				}
			});
			bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
			bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
			bootstrap.childOption(ChannelOption.TCP_NODELAY, true);
			ChannelFuture future = bootstrap.bind(ServerConfig.port).sync();
			System.out.println("启动服务器");
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
            //优雅退出，释放线程池资源
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
		
	}
}



